package com.cmz.common.utils;

import com.cmz.common.utils.snowflake.SnowflakeIdWorker;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * ID生成工具
 * @author cmz
 */
public class IDUtils {

    private IDUtils() {}

    private static final String[] CHARS = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };

    private static final SnowflakeIdWorker SNOWFLAKE_ID_WORKER = new SnowflakeIdWorker(0, 0);

    /**
     * 生成UUID
     * @return UUID(32位)
     */
    public static String getUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 生成UUID
     * @return UUID(36位)
     */
    public static String getAllUuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * 生成UUID
     * @return UUID(8位)
     */
    public static String getShortUuid() {
        StringBuilder shortBuffer = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        int bufferCount = 8;
        for (int i = 0; i < bufferCount; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(CHARS[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    /**
     * 生成基于 snowflake 算法的ID
     * @param workerId     Snowflake Worker ID
     * @param dataCenterId Data Center ID
     * @return Snowflake ID
     */
    public static String getSnowflakeId(long workerId, long dataCenterId) {
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(workerId, dataCenterId);
        return Long.toBinaryString(idWorker.nextId());
    }

    /**
     * 生成基于 snowflake 算法的ID
     * @return Snowflake ID
     */
    public static String getSnowflakeId() {
        return Long.toBinaryString(SNOWFLAKE_ID_WORKER.nextId());
    }

    /**
     * 生成指定位数的整数ID
     * @param digits 位数（应当大于0）
     * @return 随机整数
     */
    public static Integer getRandomDigitId(int digits) {
        StringBuilder result= new StringBuilder();
        for(int i=0; i<digits; i++){
            if (i==0) {
                result.append(getRandom().nextInt(9) + 1);
            } else {
                result.append(getRandom().nextInt(10));
            }
        }
        return Integer.valueOf(result.toString());
    }

    /**
     * 获取随机数生成器对象<br>
     * ThreadLocalRandom是JDK 7之后提供并发产生随机数，能够解决多个线程发生的竞争争夺。
     *
     * @return {@link ThreadLocalRandom}
     */
    public static ThreadLocalRandom getRandom() {
        return ThreadLocalRandom.current();
    }
}
